package com.gitee.lw114514.webapp_spring_1.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.IoUtil;
import com.gitee.lw114514.webapp_spring_1.pojo.User;
import com.gitee.lw114514.webapp_spring_1.service.UserService;
import com.gitee.lw114514.webapp_spring_1.service.impl.UserServiceImpl;
import com.gitee.lw114514.webapp_spring_1.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = {"http://localhost:5500", "http://127.0.0.1:5500"}, allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/api/employees")
    public List<User> list() throws FileNotFoundException {
/*        1.加载并读取user文件，获取用户数据

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("user.txt");
        ArrayList<String> lines = IoUtil.readLines(inputStream, StandardCharsets.UTF_8, new ArrayList<>());


        //2.解析用户信息并封装成user对象->list集合
        List<User> userList = lines.stream().map(line -> {
            String[] parts = line.split(",");
            Integer id = Integer.parseInt(parts[0]);
            String name = parts[1];
            Integer code = Integer.parseInt(parts[2]);
            LocalDate registration_time = LocalDate.parse(parts[3],
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            return new User(id, name, code, registration_time);
        }).toList();

        //3.返回数据json
        return userList;*/


        //调用service层，获取数据
        List<User> userList = userService.findAll();

        //返回数据json
        return userList;
    }
}
